﻿using ACS.SPiiPlusNET;
using Company.Hardware.Acs;
using Company.Share.Events;
using Company.UI.Models;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Threading;

namespace Company.UI.ViewModels
{
    public class BufferManageControlViewModel : BindableBase
    {
        //private Task _GetDataFromAcsControllerTask;
        //CancellationTokenSource tokenSource;
        // 定时器（用于更新轴相关数据）
        private DispatcherTimer UpdataBuffersTimer = new DispatcherTimer();
        private bool IsRunningUpData;
        public AcsControllerProvider AcsControllerProvider { get; private set; } // Acs控制器提供者
        public BufferManageControlModel BufferManageModel { get; private set; }
        public ObservableCollection<string> BuffersCollection { get; private set; }
        #region Commands
        public DelegateCommand<object> BufferSelectionChangedCommand { get; }
        public DelegateCommand RunBufferCommand { get; }
        public DelegateCommand StopBufferCommand { get; }
        public DelegateCommand SuspendBufferCommand { get; }
        public DelegateCommand CompileBufferCommand { get; }
        #endregion
        public BufferManageControlViewModel(AcsControllerProvider acsControllerProvider, IEventAggregator eventAggregator)
        {
            AcsControllerProvider = acsControllerProvider;
            BufferManageModel = new BufferManageControlModel();
            BuffersCollection = new ObservableCollection<string>();
            BufferSelectionChangedCommand = new DelegateCommand<object>(BufferSelectionChanged);
            RunBufferCommand = new DelegateCommand(RunBuffer);
            StopBufferCommand = new DelegateCommand(StopBuffer);
            SuspendBufferCommand = new DelegateCommand(SuspendBuffer);
            CompileBufferCommand = new DelegateCommand(CompileBuffer);

            // 事件注册
            AcsControllerProvider.AcsController.AcsDisconnecting += () =>
            {
                // 停止刷新
                UpdataBuffersTimer.Stop();
            };
            UpdataBuffersTimer.Interval = TimeSpan.FromMilliseconds(100);
            UpdataBuffersTimer.Tick += (s, e) => GetDataFromControllerCyclically();
            // 使用事件聚合器订阅
            eventAggregator.GetEvent<AcsControllerConnectedEvent>().Subscribe((obj) =>
            {
                BufferManageModel.IsConnected = obj;
                if (BufferManageModel.IsConnected)
                {
                    BuffersCollection.Clear();
                    for (int i = 0; i < AcsControllerProvider.AcsController.BuffersCount; i++)
                    {
                        BuffersCollection.Add(i.ToString());
                    }
                    // 线程启动
                    //tokenSource = new CancellationTokenSource();
                    //CancellationToken cancellationToken = tokenSource.Token;

                    //开始线程刷新数据
                    if (!IsRunningUpData)
                    {
                        //_GetDataFromAcsControllerTask = new Task(GetDataFromControllerCyclically, cancellationToken, TaskCreationOptions.LongRunning);//线程读取
                        //_GetDataFromAcsControllerTask.Start();
                        //IsRunningUpData = true;
                        //_GetDataFromAcsControllerTask.ContinueWith((t) => { IsRunningUpData = false; });
                        UpdataBuffersTimer.Start();
                        IsRunningUpData = true;
                    }
                    BufferManageModel.BuffersCount = AcsControllerProvider.AcsController.BuffersCount;
                }
            });
        }
        /// <summary>
        /// 编译Buffer
        /// </summary>
        private void CompileBuffer()
        {
            AcsControllerProvider.AcsController.CompileBuffer((ProgramBuffer)BufferManageModel.CurrentBufferId);
        }
        /// <summary>
        /// 暂停Buffer
        /// </summary>
        private void SuspendBuffer()
        {
            AcsControllerProvider.AcsController.SuspendBuffer((ProgramBuffer)BufferManageModel.CurrentBufferId);
        }
        /// <summary>
        /// 停止Buffer
        /// </summary>
        private void StopBuffer()
        {
            AcsControllerProvider.AcsController.StopBuffer((ProgramBuffer)BufferManageModel.CurrentBufferId);
        }
        /// <summary>
        /// 运行Buffer
        /// </summary>
        private void RunBuffer()
        {
            AcsControllerProvider.AcsController.RunBuffer((ProgramBuffer)BufferManageModel.CurrentBufferId);
        }

        /// <summary>
        /// 选择当前Buffer Id
        /// </summary>
        /// <param name="obj"></param>
        private void BufferSelectionChanged(object obj)
        {
            int bufferIndex = (int)obj;
            BufferManageModel.CurrentBufferId = bufferIndex;
        }

        private void GetDataFromControllerCyclically()
        {
            if (AcsControllerProvider.AcsController.IsConnected)
            {
                //程序状态
                var programStates = AcsControllerProvider.AcsController.GetProgramState((ProgramBuffer)BufferManageModel.CurrentBufferId);
                //buffer错误代码
                var bufferErrorCode = AcsControllerProvider.AcsController.GetProgramError((ProgramBuffer)BufferManageModel.CurrentBufferId);
                //buffer错误信息
                var bufferErrorMessage = AcsControllerProvider.AcsController.GetErrorString(BufferManageModel.BufferState.BufferErrorCode);
                //Application.Current.Dispatcher.BeginInvoke(new Action(() =>
                // {
                BufferManageModel.BufferState.ProgramStates = programStates;
                BufferManageModel.BufferState.Auto = BufferManageModel.BufferState.ProgramStates == ProgramStates.ACSC_PST_AUTO;
                BufferManageModel.BufferState.Compile = BufferManageModel.BufferState.ProgramStates == ProgramStates.ACSC_PST_COMPILED;
                BufferManageModel.BufferState.Debug = BufferManageModel.BufferState.ProgramStates == ProgramStates.ACSC_PST_DEBUG;
                BufferManageModel.BufferState.None = BufferManageModel.BufferState.ProgramStates == ProgramStates.ACSC_NONE;
                bool isRun1 = BufferManageModel.BufferState.ProgramStates == (ProgramStates.ACSC_PST_RUN | ProgramStates.ACSC_PST_COMPILED);
                bool isRun2 = BufferManageModel.BufferState.ProgramStates == (ProgramStates.ACSC_PST_RUN | ProgramStates.ACSC_PST_SUSPEND | ProgramStates.ACSC_PST_COMPILED);
                if (isRun1 || isRun2)
                {
                    BufferManageModel.BufferState.Running = true;
                    BufferManageModel.BufferState.Compile = true;
                    if (isRun2) BufferManageModel.BufferState.Suspend = true; else BufferManageModel.BufferState.Suspend = false;
                }
                else
                {
                    BufferManageModel.BufferState.Running = false;
                    BufferManageModel.BufferState.Suspend = false;
                }
                BufferManageModel.BufferState.BufferErrorCode = bufferErrorCode;
                BufferManageModel.BufferState.BufferErrorMessage = bufferErrorMessage;
                // }));
            }
        }
    }
}
